package com.seven.smartsnmp.handler;

import com.seven.smartsnmp.base.MyException;
import com.seven.smartsnmp.snmp.SNMPAPI;
import com.seven.smartsnmp.snmp.SNMPFactory;
import com.seven.smartsnmp.utils.SNMPUtils;
import net.percederberg.mibble.MibValueSymbol;
import net.percederberg.mibble.snmp.SnmpObjectType;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;

/**
 * @author Admin
 */

public class SetHandler {


    public  void setValue(String oid, String nodeOid, String value, Snmp snmp, Target target) throws MyException {
        try {
            MibValueSymbol mibValueSymbol = SNMPFactory.getInstance().getMibSymbolByOid(oid);
            SnmpObjectType snmpObjectType = (SnmpObjectType) mibValueSymbol.getType();
            Variable var = SNMPUtils.getVariable(snmpObjectType.getSyntax(), value);
            PDU pdu = SNMPUtils.createPdu(target.getVersion());
            pdu.add(new VariableBinding(new OID(oid + "." + nodeOid), var));
            ResponseEvent responseEvent = snmp.set(pdu, target);
            SNMPUtils.checkSNMPErro(responseEvent);
            PDU respdu = responseEvent.getResponse();
            VariableBinding variableBinding = respdu.get(0);
            Variable variable = variableBinding.getVariable();
            String str = variable.toString();

            if (str.equalsIgnoreCase("noSuchInstance") || str.equalsIgnoreCase("No such name") || str.equalsIgnoreCase("noSuchObject")) {
                throw new MyException(SNMPAPI.MessageNoSuchOID);
            }
        } catch (Exception exception) {
            String msg = "修改 oid的值出错,oid名:" + oid + ",错误:" + exception.getMessage();
            throw new MyException(msg);
        }
    }

    /**
     * 设置
     *
     * @param oid
     * @param variable
     * @param snmp
     * @param target
     * @throws MyException
     */
    public void setValue(String oid, Variable variable, Snmp snmp, Target target) throws MyException {
        try {
            PDU pdu = SNMPUtils.createPdu(target.getVersion());
            pdu.add(new VariableBinding(new OID(oid), variable));
            ResponseEvent event = snmp.set(pdu, target);
            SNMPUtils.checkSNMPErro(event);
            snmp.close();
        } catch (Exception e) {
            String msg = "修改 oid的值出错,oid名:" + snmp + ",错误:" + e.getMessage();
            throw new MyException(msg);
        }finally {
            SNMPUtils.closeSnmp(snmp);
        }
    }

}
